package com.example.springboot.dao.imp;

import com.example.springboot.bean.ShoppingRecord;
import com.example.springboot.dao.ShoppingRecordDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.GeneratedValue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by tang on 2018/3/8.
 */
@Service
public class ShoppingRecordDaoImp implements ShoppingRecordDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public ShoppingRecord addShoppingRecord(ShoppingRecord shoppingRecord) {

        String sql = "insert into book_shopping_records(book_name,customer_name,date) values(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                int count = 1;
                psst.setString(count++, shoppingRecord.getBookName());
                psst.setString(count++, shoppingRecord.getCustomerName());
                psst.setDate(count++, shoppingRecord.getDate());
                return psst;
            }
        }, keyHolder);

        shoppingRecord.setId(keyHolder.getKey().intValue());
        return shoppingRecord;
    }

    @Override
    @Transactional
    public List<ShoppingRecord> batchAddShoppingRecord(List<ShoppingRecord> shoppingRecordList) {
        String sql = "insert into book_shopping_records(book_name,customer_name,date) values(?,?,?)";
        for (ShoppingRecord shoppingRecord : shoppingRecordList) {
            GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                    int count = 1;
                    psst.setString(count++, shoppingRecord.getBookName());
                    psst.setString(count++, shoppingRecord.getCustomerName());
                    psst.setDate(count++, shoppingRecord.getDate());
                    return psst;
                }
            }, generatedKeyHolder);
            shoppingRecord.setId(generatedKeyHolder.getKey().intValue());
        }

        return shoppingRecordList;
    }


}
